<template>
  <div class="layout">
    <p class="crumbs">
      <router-link :to="{
        path: '/project/dataset/label/lis',
        query: { id: $route.query.id }
      }">数据标注</router-link>
      <span>/{{ $route.query.labelId ? "修改" : "新增" }}</span>
      <!-- <strong class="explain-back">
        <el-button type="text" icon="el-icon-right" class="back" @click="
          $router.push({
            path: '/intelligenceproject/model-deploy/edge/lis',
            query: {
              id: $route.query.id,
            }
          })
        "></el-button>
      </strong> -->
    </p>
    <div class="introduce clearfix">
      <el-form
        class="form-box"
        ref="form"
        :model="addForm"
        :rules="submitRules"
        label-width="124px"
        label-position="left"
      >
        <h2 class="title-echelon1">基础信息</h2>
        <el-form-item label="选择数据集" prop="datasetId">
          <plug-dataset 
            :defaultDatasets="addForm.datasetId" 
            :defaultDatasetsName="defaultDatasetsName" 
            ref="plugDataset"
            @infoDataset="infoDataset" />
          <!-- <el-select
            v-model="addForm.datasetId"
            @change="changeDataSet"
            placeholder="请选择"
            :disabled="$route.query.labelId != null"
            style="width: 100%"
          >
            <el-option
              v-for="item in datasetsMap"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="addForm.name"
            maxlength="40"
            minlength="1"
            clearable
            placeholder="长度1-40个字符"
            size="medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="标注类型" prop="annType">
          <el-select
            v-model="addForm.annType"
            :disabled="isInherit == 1"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option label="图像分类" value="图像分类"></el-option>
            <el-option label="物体检测" value="物体检测"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-input
            v-for="(e, i) in addForm.labels"
            :key="i"
            v-model="e.name"
            maxlength="40"
            minlength="1"
            placeholder="最多可输入40字"
            size="medium"
            :disabled="!!e.id"
          >
            <el-button
              slot="append"
              icon="el-icon-delete"
              :disabled="!!e.id"
              v-if="addForm.labels.length != 1"
              @click="delLabels(i)"
            />
          </el-input>
          <el-button type="text" icon="el-icon-plus" @click="addLabels"
            >添加</el-button
          >
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            maxlength="100"
            type="textarea"
            show-word-limit
            v-model="addForm.description"
            placeholder="最多可输入100字"
          ></el-input>
        </el-form-item>
        <el-form-item label=" ">
          <v-btn @click="reset">重置</v-btn>
          <v-btn type="primary" @click="submitReject">确认</v-btn>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  addAnntasks,
  putAnntasks,
  getAnntasksDetail,
  // importAnntasks,
  clearAnntasks
} from "@/api/label";
import { delBatchFile } from "@/api/file";
import { getAllDatasets } from "@/api/dataset";
import { getJsonFile } from "./module/tool";
import plugDataset from './module/plug-in-dataset'
export default {
  data() {
    let tempIndex = 0;
    let validatorLabels = (rule, val, callback) => {
      tempIndex = 0;
      for (let i = 0; i < this.addForm.labels.length; i++) {
        if (!this.addForm.labels[i].name) {
          tempIndex++;
        }
      }
      if (tempIndex != 0) {
        callback(new Error("请填写标签名"));
      } else {
        callback();
      }
    };
    let validatorDataset = (rule, val, callback) => {
      callback();
    }
    return {
      addForm: {
        datasetId: "",
        labels: [{ name: "" }],
        name: "",
        annType: "",
        description: "",
        projectId: this.$route.query.id,
      },
      defaultDatasetsName: '',
      pageData: {
        projectId: this.$route.query.id,
        visibility: "1",
      },
      isInherit: 0,
      datasetsMap: [],
      resetAddForm: {},
      submitRules: {
        name: [
          { required: true, message: "请填写名称" },
          { required: true, min: 1, max: 40, message: "长度在1到40个字符" },
        ],
        annType: [
          { required: true, message: "请选择标注类型", trigger: "change" },
        ],
        datasetId: [
          // { required: true, message: "请选择数据集", trigger: "change" },
          { required: true, validator: validatorDataset },
        ],
        labels: [{ required: true, validator: validatorLabels }],
      },
    };
  },
  components: { plugDataset },
  methods: {
    reset() {
      if (this.isInherit == 1) {
        this.addForm.name = ''
        this.addForm.description = ''
        this.addForm.labels = this.addForm.labels.filter(e => !!e.id)
      } else {
        this.addForm = JSON.parse(this.resetAddForm);
      }
    },
    infoDataset (data) {
      this.addForm.datasetId = data.id
      this.addForm.datasetVersionId = data.currentVersionId
      this.initRecorded(data.id)
      console.log(data)
    },
    async getData() {
      if (this.$route.query.labelId) {
        let res = await getAnntasksDetail({ id: this.$route.query.labelId });
        for (let i in res) {
          this.addForm[i] = res[i];
        }
        this.defaultDatasetsName = res.dataset.name
        
      }
      await this.getDataSets();
      if (this.$route.query.datasetId) {
        this.addForm.datasetId = this.$route.query.datasetId;
        this.changeDataSet(this.$route.query.datasetId);
      }
      if (this.$route.query.datasetId) {
        this.defaultDatasetsName = this.$route.query.datasetsName
      }
    },
    async getDataSets() {
      let res = await getAllDatasets(this.pageData);
      this.datasetsMap = res;
    },
    changeDataSet(e) {
      let checkedTmp = this.datasetsMap.filter((ele) => ele.id == e);
      this.initRecorded(e)
      if (checkedTmp && checkedTmp[0] && checkedTmp[0].currentVersionId) {
        this.addForm.datasetVersionId = checkedTmp[0].currentVersionId;
      } else {
        // this.$message.error("该数据集暂无以发布的版本，请选择其他数据集。");
      }
    },
    delLabels(index) {
      if (this.addForm.labels.length > 1) {
        this.addForm.labels.splice(index, 1);
      }
    },
    addLabels() {
      this.addForm.labels.push({ name: "" });
    },
    // async inform(id, bizId, fn) {
    //   await getJsonFile(this, bizId, "recorded.json", async (e) => {
    //     let data = { id };
    //     if (e.labelNames && e.labelNames.length) {
    //       data.labelNames = e.labelNames.map((item) => item.name);
    //     }
    //     if (e.annotations && e.annotations.length) {
    //       data.annotations = e.annotations.map((item) => {
    //         return {
    //           url: item.fileUrl,
    //           labelNames: item.labelNames.map((ele) => ele.name),
    //         };
    //       });
    //     }
        // if (e.labelNames && e.annotations) {
        //   await importAnntasks(data);
        // }
      //   if (fn) {
      //     fn();
      //   }
      // });
    // },
    verifyLabels() {
      let l = this.addForm.labels.map((e) => e.name);
      let hash = {};
      l.forEach((e, i) => {
        if (!e) {
          l.splice(i, 1);
        }
      })
      for (let i in l) {
        if (hash[l[i]]) {
          return true;
        }
        hash[l[i]] = true;
      }
      return false;
    },
    async toBeEmpty (id) {
      // let res = await this.$isDel('操作清空后当前的标注数据无法找回，请谨慎操作');
      // if (res) {
        await clearAnntasks({ id })
        let info = await this.$myInfo(this);
        await delBatchFile([{
          bizId: this.addForm.datasetId,
          relativePath: `editable/.annotation`,
          tenantId: info.orgId,
          type: 'dataset'
        }])
      //   this.getData()
      // }
    },
    submitReject() {
      this.$refs["form"].validate(async (valid, err) => {
        if (valid) {
          let path = "/project/dataset/label/working";
          let query = {
            id: this.$route.query.id,
          };
          if (this.addForm.annType == "图像分类") {
            path = "/project/dataset/label/classify";
          }
          if (this.verifyLabels()) {
            this.$message.error("标签名有重复");
            return;
          }
          // let tempLabels = []
          // this.addForm.labels.forEach(e => {
          //   if (!this.$route.query.labelId) {
          //     if (e.name && !e.id) {
          //       tempLabels.push(e)
          //     }
          //   }
          // })
          // this.addForm.labels = tempLabels
          if (this.$route.query.labelId) {
            await putAnntasks(this.addForm);
            query.taskId = this.$route.query.labelId;
            this.$router.push({ path, query });
          } else {
            let res = await addAnntasks(this.addForm);
            query.taskId = res.id;
            if (this.isInherit == 2) {
              await this.toBeEmpty(res.id)
              this.$router.push({ path, query });
            } else {
              // await this.inform(res.id, this.addForm.datasetId, () => {
                this.$router.push({ path, query });
              // });
            }
          }
        } else {
          console.log("error submit!!", err);
          return false;
        }
      });
    },
    async initRecorded (bizId) {
      await getJsonFile(this, bizId, "recorded.json", async (e) => {
        this.isInherit = 0
        this.addForm.labels = [{name: ''}]
        this.addForm.annType = ''
        if (e.labelNames && e.labelNames.length) {
          this.$messesDialog({
            btnPreText: "继承历史标注",
            btnNextText: "重新标注",
            message: "请确认重新标注，或是继承历史标注信息"
          }).then(boolean => {
            if (!boolean) {
              this.addForm.labels = e.labelNames
              if (e.type) {
                this.addForm.annType = e.type
                this.isInherit = 1
              }
            } else {
              this.addForm.labels = [{name: ''}]
              this.addForm.annType = ''
              // this.$refs.plugDataset.datasetName = ''
              this.isInherit = 2
            }
          })
        } else {
          console.log(this.isInherit)
          this.isInherit = 2
        }
        // if (e.labelNames && e.labelNames.length) {
        //   data.labelNames = e.labelNames.map((item) => item.name);
        // }
      })
    }
  },

  created() {},
  mounted() {
    this.getData();
    this.resetAddForm = JSON.stringify(this.addForm);
    if (this.$route.query.labelId) {
      this.isInherit = 1
    }
  },
  destroyed() {},
};
</script>

<style lang="less" scoped>
.layout {
  // padding: 0 16px;
  // navbar
  .introduce {
    .form-box {
      max-width: 936px;
    }
    background: #fff;
    margin: 16px;
    padding: 16px 32px;
    .title-echelon1 {
      font-size: 16px;
      color: @deepgray;
      margin-bottom: 20px;
      line-height: 22px;
      padding-bottom: 4px;
      border-bottom: 1px solid #e4e7ed;
    }
  }
}
</style>